package cn.nfwx.tv.controller.me;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.MineSubcriptionAdapter2;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.manager.SubscriptionManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.SubscriptModel;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.LoadView;

public class MineSubscriptionController {
    private Context mContext;
    private BaseFragment mFragment;
    private RecyclerView mRecyclerView;
    private MineSubcriptionAdapter2 mineSubcriptionAdapter2;
    private LoadView mLoadView;
    private TwinklingRefreshLayout trl_mine;
    private View notDataView;
    private List<SubscriptModel> hotSubscription = new ArrayList<>();
    private List<SubscriptModel> mySubscription = new ArrayList<>();
    private int currentSubTabSelect;
    private String requestHotSubscriptionCommand, requestMySubscriptionCommand, requestDelSubscriptionCommand, requestAddSubscriptionCommand;

    public MineSubscriptionController(Context mContext, BaseFragment fragment) {
        this.mContext = mContext;
        this.mFragment = fragment;
    }

    public void init(RecyclerView recyclerView, LoadView loadView, final TwinklingRefreshLayout trl_mine, View notDataView) {
        mRecyclerView = recyclerView;
        mLoadView = loadView;
        this.trl_mine = trl_mine;
        this.notDataView = notDataView;

        if (mineSubcriptionAdapter2 == null) {
            mineSubcriptionAdapter2 = new MineSubcriptionAdapter2();
        }
        mRecyclerView.setAdapter(mineSubcriptionAdapter2);

        mineSubcriptionAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (adapter.getItemViewType(position) == MineSubcriptionAdapter2.ITEM_PART2) {
                    Object object = adapter.getData().get(position);
                    if (object instanceof SubscriptModel.LoadMore) {
                        SubscriptModel.LoadMore model = (SubscriptModel.LoadMore) object;
                        for (SubscriptModel subscriptModel : mySubscription) {
                            if (subscriptModel.getSubject_id() == model.subject_id) {
                                boolean isLoadMore = model.isLoadMore;
                                List<Object> objects = subscriptModel.getMoreList();
                                TextView textView = ((TextView) view.findViewById(R.id.tv_load_more));
                                if (isLoadMore) {
                                    for (int j = 0; j < objects.size(); j++) {
                                        adapter.remove(position - 1 - j);
                                    }
                                    model.isLoadMore = false;
                                    textView.setText(R.string.load_more);
                                } else {
                                    adapter.addData(position, objects);
                                    model.isLoadMore = true;
                                    textView.setText(R.string.ellipsis);
                                }
                                break;
                            }
                        }
                    }
                } else if (adapter.getData().get(position) instanceof TvProgram) {
                    TvProgram tvProgram = (TvProgram) adapter.getData().get(position);
                    if (TextUtils.isEmpty(tvProgram.getUrl())) {
                        ToastUtil.show(mContext, "无对应节目");
                        return;
                    }
                    PlayEvents events = new PlayEvents(tvProgram.getProgram_id(), tvProgram.getUrl(), null, tvProgram.getProgram_name(), 0);
                    if (mFragment.getParentFragment() instanceof MineFragment) {
                        MineFragment mineFragment = (MineFragment) mFragment.getParentFragment();
                        mineFragment.isBackEvent = false;
                        events.setFragment(PlayEvents.MINE);
                        events.setMePosition(MineFragment.POSITION_SUBSCRIPT);
                        events.setTag("mineFragment");
                    }
                    EventBus.getDefault().post(events);
                }
            }
        });


        mineSubcriptionAdapter2.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (adapter.getData().get(position) instanceof SubscriptModel) {
                    switch (view.getId()) {
                        case R.id.subscription_cancle_btn:
                            if (AccountHelper.getInstance().isLogin(mContext)) {
                                final SubscriptModel subscriptModel = (SubscriptModel) adapter.getData().get(position);
                                if (subscriptModel.isFousc()) {
                                    mLoadView.startLoading(trl_mine);
                                    requestDelSubscriptionCommand = SubscriptionManager.requestDelSubscription(mContext, subscriptModel.getSubject_id(), responseListener);
                                }
                            }
                            break;
                        case R.id.subscription_btn:
                            if (AccountHelper.getInstance().isLogin(mContext)) {
                                final SubscriptModel subscriptModel = (SubscriptModel) adapter.getData().get(position);
                                if (!subscriptModel.isFousc()) {
                                    mLoadView.startLoading(trl_mine);
                                    requestAddSubscriptionCommand = SubscriptionManager.requestAddSubscription(mContext, subscriptModel.getSubject_id(), responseListener);
                                }
                            }
                            break;
                    }
                }
            }
        });
    }

    public void setCurrentSelect(int currentSelect) {
        currentSubTabSelect = currentSelect;
    }

    public void bindSubscriptData() {


        bindSubscriptData(currentSubTabSelect);
    }

    public void bindAdapter() {
        mLoadView.removeParentView(trl_mine);
        mRecyclerView.setAdapter(mineSubcriptionAdapter2);
    }

    /**
     * 订阅数据绑定
     *
     * @param position
     */
    public void bindSubscriptData(int position) {
        if (position == 0) {
            mineSubcriptionAdapter2.setEmptyView(new View(mContext));
            mineSubcriptionAdapter2.setNewData(new ArrayList<Object>());
            if (mySubscription.isEmpty()) {
                //mLoadView.startLoading(trl_mine);
                requestMySubscriptionCommand = SubscriptionManager.requestMySubscriptionList(mContext, responseListener);
            } else {
                List<Object> objects = new ArrayList<>();
                for (SubscriptModel subscriptModel : mySubscription) {
                    objects.addAll(subscriptModel.getEllipsisList());
                }
                mineSubcriptionAdapter2.setNewData(objects);
                trl_mine.finishRefreshing();
            }
        } else if (position == 1) {
            mineSubcriptionAdapter2.setEmptyView(new View(mContext));
            mineSubcriptionAdapter2.setNewData(new ArrayList<Object>());
            if (hotSubscription.isEmpty()) {
                //mLoadView.startLoading(trl_mine);
                requestHotSubscriptionCommand = SubscriptionManager.requestHotSubscriptionList(mContext, responseListener);
            } else {
                List<Object> objects = new ArrayList<>();
                objects.addAll(hotSubscription);
                mineSubcriptionAdapter2.setNewData(objects);
                trl_mine.finishRefreshing();
            }
        }
    }

    ResponseListener<String> responseListener = new ResponseListener<String>() {
        @Override
        public void onResponse(final String requestTag, final String response) {
            if (requestTag.equals(requestMySubscriptionCommand)) {
                Result<List<SubscriptModel>> result = JSON.parseObject(response, new TypeReference<Result<List<SubscriptModel>>>() {
                }.getType());
                if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                    mySubscription.clear();
                    mySubscription.addAll(result.getData());
                    final List<Object> objects = new ArrayList<>();
                    for (SubscriptModel subscriptModel : mySubscription) {
                        subscriptModel.setFousc(true);
                        objects.addAll(subscriptModel.getEllipsisList());
                    }
                    ThreadHelper.post(new Runnable() {
                        @Override
                        public void run() {
                            if (objects.isEmpty()) {
                                mineSubcriptionAdapter2.setEmptyView(notDataView);
                            } else {
                                mineSubcriptionAdapter2.setNewData(objects);
                            }
                        }
                    });
                }
            } else if (requestTag.equals(requestHotSubscriptionCommand)) {
                Result<List<SubscriptModel>> result = JSON.parseObject(response, new TypeReference<Result<List<SubscriptModel>>>() {
                }.getType());
                if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                    hotSubscription.clear();
                    hotSubscription.addAll(result.getData());
                    final List<Object> objects = new ArrayList<>();
                    for (SubscriptModel subscriptModel : hotSubscription) {
                        subscriptModel.setFousc(false);
                        for (SubscriptModel mySubscriptModel : mySubscription) {
                            if (subscriptModel.getSubject_id() == mySubscriptModel.getSubject_id()) {
                                subscriptModel.setFousc(true);
                                break;
                            }
                        }
                        objects.add(subscriptModel);
                    }
                    ThreadHelper.post(new Runnable() {
                        @Override
                        public void run() {
                            if (objects.isEmpty()) {
                                mineSubcriptionAdapter2.setEmptyView(notDataView);
                            } else {
                                mineSubcriptionAdapter2.setNewData(objects);
                            }
                        }
                    });
                }
            } else if (requestTag.equals(requestDelSubscriptionCommand)
                    || requestTag.equals(requestAddSubscriptionCommand)) {
                Result<SubscriptModel> result = JSON.parseObject(response, new TypeReference<Result<SubscriptModel>>() {
                }.getType());
                if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                    if (currentSubTabSelect == 0) {
                        mySubscription.clear();
                        hotSubscription.clear();
                        ThreadHelper.post(new Runnable() {
                            @Override
                            public void run() {
                                bindSubscriptData();
                            }
                        });
                    } else if (currentSubTabSelect == 1) {
                        mySubscription.clear();
                        for (SubscriptModel subscriptModel : hotSubscription) {
                            if (subscriptModel.getSubject_id() == result.getData().getSubject_id()) {
                                if (requestTag.equals(requestDelSubscriptionCommand)) {
                                    subscriptModel.setFousc(false);
                                } else if (requestTag.equals(requestAddSubscriptionCommand)) {
                                    subscriptModel.setFousc(true);
                                }
                                break;
                            }
                        }
                        final List<Object> objects = new ArrayList<>();
                        objects.addAll(hotSubscription);
                        ThreadHelper.post(new Runnable() {
                            @Override
                            public void run() {
                                mineSubcriptionAdapter2.setNewData(objects);
                            }
                        });
                    }
                }

            }
        }

        @Override
        public void onError(final String requestTag, Throwable t) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (requestTag.equals(requestMySubscriptionCommand)) {
                        mLoadView.loadError(trl_mine);
                        trl_mine.finishRefreshing();
                    } else if (requestTag.equals(requestHotSubscriptionCommand)) {
                        mLoadView.loadError(trl_mine);
                        trl_mine.finishRefreshing();
                    }
                }
            });
        }

        @Override
        public void onFinish() {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    mLoadView.removeParentView(trl_mine);
                    trl_mine.finishRefreshing();
                }
            });
        }
    };


}
